package org.jaaksi.customviewdemo

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_test_heartrate.*
import org.jaaksi.customviewdemo.chart.Scale
import kotlin.random.Random

class TestHeartRateActivity : AppCompatActivity() {
    private val dataPoints = mutableListOf<Float>()

    private val initArrs = mutableListOf(2f, 7f, 1f)

    private var index = 0

    private val maxWaveBand = 9

    private val handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            when {
                msg.what % 2 == 0 -> dataPoints.add(getPeakPoint())
                else -> dataPoints.add(getDeclinePoint())
            }
            // 只保留多一个点，用来做动画
            if (dataPoints.size > chart.maxPointSize + 1) {
                dataPoints.removeAt(0)
            }
            setScale()
            chart.setData(dataPoints, true)
            sendEmptyMessageDelayed(index++, 310)
        }
    }

    private fun getDeclinePoint(): Float {
        return Random.nextInt(0, 3).toFloat()
    }


    private fun getPeakPoint(): Float {
        return Random.nextInt(7, 20).toFloat()
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test_heartrate)
        btn_start.setOnClickListener {
            start()
        }

        btn_stop.setOnClickListener {
            stop()
        }

        btn_end.setOnClickListener {
            handler.removeCallbacksAndMessages(null)
            chart.setData(dataPoints)
        }
        chart.maxWaveBand = maxWaveBand
    }

    private fun setScale() {
        chart.setScale(Scale(dataPoints.minOrNull()!! - 5, dataPoints.maxOrNull()!! + 1))

    }

    private fun start() {
        stop()
        // 至少3个点，才开始
        dataPoints.addAll(initArrs)
        index = 2
        setScale()
        chart.setData(dataPoints, true)
        handler.sendEmptyMessageDelayed(index++, 610)
    }

    private fun stop() {
        handler.removeCallbacksAndMessages(null)
        dataPoints.clear()
        chart.setData(dataPoints)
    }


}